﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using Rodunu.Movies.Contracts;
using Rodunu.Movies.Data;
using Rodunu.Movies.Interfaces.Subscriptions;

namespace Rodunu.Movies.Logic.Subscriptions
{
    public class SubscriptionsLogic : Repository<ServiceSubscriptions>, ISubscriptions
    {
        public ServiceSubscriptions GetSubscription(UserInfo userId, Services serviceId)
        {
            return
                DBHelper.GetCurrentSession().CreateCriteria(typeof(ServiceSubscriptions))
                .Add(Restrictions.Eq("UserId", userId))
                .Add(Restrictions.Eq("Services", serviceId))
                .UniqueResult<ServiceSubscriptions>();
        }

        public IList<ServiceSubscriptions> GetActiveSubscriptions(UserInfo id)
        {
            return
                DBHelper.GetCurrentSession().CreateCriteria(typeof(ServiceSubscriptions))
                .Add(Restrictions.Eq("UserId", id))
                .Add(Restrictions.Eq("Enabled", true))
                .List<ServiceSubscriptions>();
        }

        public bool IsActiveService(UserInfo user, ExternalServices externalService)
        {
            ServiceSubscriptions subscriptions = (from service in GetActiveSubscriptions(user)
                                                  where service.Services.Id == Convert.ToInt64(externalService)
                                                  select service).SingleOrDefault();
            if (subscriptions != null)
                return subscriptions.Enabled;
            return false;
        }
    }
}
